package com.abcdefg.demo.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumeMQ {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建工厂连接
        ConnectionFactory factory = new ConnectionFactory();

        //2. 设置参数
        factory.setHost("123.249.25.146");//ip 默认值localhost
        factory.setPort(5672); //默认值5672
        factory.setVirtualHost("java");//虚拟机名称,

        factory.setUsername("ABCDEFG");//⽤⼾名
        factory.setPassword("20041106");//密码

        //3. 创建连接Connection
        Connection connection = factory.newConnection();

        //4. 创建channel通道
         Channel channel = connection.createChannel();
         //5. 声明队列
         channel.queueDeclare("hello", true, false, false, null);
        //6.接受消息，并进行消费
        DefaultConsumer consumer=new DefaultConsumer(channel){
        /**
         *   回调⽅法, 当收到消息后, 会⾃动执⾏该⽅法
         *  1. consumerTag: 标识
         *  2. envelope: 获取⼀些信息, 交换机, 路由key
         *  3. properties:配置信息
         *  4. body:数据
         */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
            }
        };

        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 1.queue: 队列名称
         * 2.autoAck: 是否⾃动确认, 消费者收到消息之后,⾃动和MQ确认
         * 3.callback: 回调对象
         */
        channel.basicConsume("hello",true,consumer);
        //加入休眠是为了显示出所有消费信息
        Thread.sleep(2000);
        //7.释放资源
        channel.close();
        connection.close();

    }
}
